package com.hunktimes.wholesale.vm

import androidx.lifecycle.MediatorLiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import androidx.lifecycle.Transformations
import com.hunktimes.wholesale.base.BaseViewModel
import com.hunktimes.wholesale.extension.launch
import com.hunktimes.wholesale.net.WholeSaleRepository
import com.hunktimes.wholesale.net.model.ApiResponse
import com.hunktimes.wholesale.net.model.ForgetPwd
import com.hunktimes.wholesale.net.model.GetCaptcha
import com.hunktimes.wholesale.util.L
import kotlinx.coroutines.flow.combineTransform

/**
 * Author: Delete
 * Date: 2020/8/10 10:51
 * Description:
 *
 */
class ForgetPwdVM : BaseViewModel() {
    val phone = MutableLiveData<String>()
    val pwd = MutableLiveData<String>()
    val pwdAgain = MutableLiveData<String>()
    val smsCode = MutableLiveData<String>()

    val smsCodeResult = MutableLiveData<ApiResponse<Any?>>()

    //val text = Transformations.map()
    val pwdDlc = MediatorLiveData<Int>()
    val pwdDlcObs = Observer<Any> {
        pwdDlc.value = pwdDlc.value ?: 0 + 1
    }

    init {
        pwdDlc.addSource(pwd, pwdDlcObs)
        pwdDlc.addSource(pwdAgain, pwdDlcObs)
    }

    val forgetPwdResult = MutableLiveData<ApiResponse<Any?>>()
    fun forgetPwd() {
        launch({
            val phone = phone.value!!
            val pwd = pwd.value!!
            val smsCode = smsCode.value!!
            val forgetPwd = ForgetPwd(phone, pwd, smsCode)
            val forgetPwdRes = WholeSaleRepository.forgetPwd(forgetPwd)
            forgetPwdResult.value = forgetPwdRes
        })

    }


    fun sendSmsCode() {
        launch({
            val phone = phone.value!!
            val smsResult = WholeSaleRepository.getSmsCode(GetCaptcha(phone))
            smsCodeResult.value = smsResult
        }, { e ->
            L.d("ForgetPwdVM sendSmsCode error -> ${e.message}")
        })
    }

}